package com.yeskery.nut.web.demo.interceptor;

import com.yeskery.nut.annotation.bean.*;
import com.yeskery.nut.annotation.environment.Value;
import com.yeskery.nut.core.RequestApplicationContext;
import com.yeskery.nut.extend.i18n.MessageService;
import com.yeskery.nut.extend.oauth.AccessTokenGenerator;
import com.yeskery.nut.web.demo.common.Constants;
import com.yeskery.nut.web.demo.common.R;

import javax.annotation.PostConstruct;
import java.util.Set;

/**
 * OAuth拦截器
 * @author YESKERY
 * 2024/11/6
 */
@Component
public class OAuthInterceptor extends com.yeskery.nut.extend.oauth.OAuthInterceptor {

    @Value("${server.unauth.uris}")
    private Set<String> unAuthUris;

    @LazyInject
    @Qualifier("accessTokenGenerator")
    @Autowired
    private AccessTokenGenerator accessTokenGenerator;

    @Autowired
    private MessageService messageService;

    @PostConstruct
    public void init() {
        unAuthUris.forEach(this::addNoAuthPath);
        addAuthPath("/oauth/loginUser");
    }

    @LazyInitialized
    public void lazyInit() {
        setAuthenticate(createAuthenticate(accessTokenGenerator, v -> RequestApplicationContext.putResource(Constants.OAUTH_TOKEN_KEY, v)));
        setUnauthorizedHandler((request, response, execution) -> response.writeJsonFromObject(R.fail(messageService.getMessage("oauth.token.invalid"))));
    }
}
